#!/usr/bin/env python
'''
Pipe - This uses a virtual TTY for communicating with 
Toggler or similar front end. 

Author: Elias Bakken
email: elias(dot)bakken(at)gmail(dot)com
Website: http://www.thing-printer.com
License: GNU GPL v3: http://www.gnu.org/copyleft/gpl.html

 Debrew is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Debrew is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with Redeem.  If not, see <http://www.gnu.org/licenses/>.
'''

import select
import logging
import os
import re
import subprocess
from multiprocessing import Process

class Pipe:
    def __init__(self, q, prot):
        self.prot = prot

        pipe_0 = "/dev/toggle_1"
        #pipe_1 = "/dev/"+self.prot+"_1"
        #p = subprocess.Popen(["tty0tty", pipe_0, pipe_1], stderr=subprocess.PIPE)
        #line = p.stderr.readline()
        self.fifo = os.open(pipe_0, os.O_RDWR)

        self.running = True
        self.t = Process(target=self.get_message, args=(q,))
        self.send_response = True
        self.t.daemon = True
        self.t.start()		


    ''' Loop that gets messages and pushes them on the queue '''
    def get_message(self, q):
        while self.running:
            ret = select.select( [self.fifo],[],[], 1.0 )
    	    if ret[0] == [self.fifo]:
                message = self.readline_custom()
                if len(message)>0:
                    print "Fetched "+message
                    q.put(message)

    def send_message(self, message):
        if self.send_response: 
            if message[-1] != "\n":
                message += "\n"
                os.write(self.fifo, message)

    def close(self):
        self.running = False
        self.t.join()
        self.fifo.close()

    def readline_custom(self):
        message = ""

        while True:
            cur_char = os.read(self.fifo, 1)
            #Check for newline char    
            if (cur_char == '\n' or cur_char == ""):
                return message;
            message = message + cur_char


